package com.bk.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import com.bk.base.BaseServlet;
import com.bk.model.Cart;
import com.bk.model.CartItem;
import com.bk.model.Category;
import com.bk.model.Product;
import com.bk.utils.CommonsUtils;
import com.bk.utils.PageBean;
import com.sun.mail.imap.protocol.Item;

/**
 * Servlet implementation class ProductServlet
 */
public class ProductServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
       
   /**
    * 分页显示商品数据
   * @author: 千锋讲师张增强
   * @createTime: 2017年7月4日 下午2:13:35
   * @history:
   * @param request
   * @param response
   * @throws ServletException
   * @throws IOException void
 * @throws SQLException 
 * @throws NumberFormatException 
    */
	protected void showProductByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, NumberFormatException, SQLException {
		// TODO Auto-generated method stub
		//currentPage  pageSize cid
		String cid = request.getParameter("cid");
		int pageSize=6;
		int currentPage=1;//从导航栏链接过来
		//从页面获取
		String currentPage_ = request.getParameter("currentPage");//从商品的分页页面过来
		if(currentPage_!=null){
			currentPage=Integer.parseInt(currentPage_);
		}
		
		
		
		//调用service查询数据
		PageBean pb = productServiceImpl.findProductByPage(currentPage, pageSize, Integer.parseInt(cid));
		
		//把 pageBean放到 request域对象
		request.setAttribute("cid", cid);
		request.setAttribute("pb", pb);
		request.getRequestDispatcher("product_list.jsp").forward(request, response);
	}
	/**
	 * 分页加商品搜索
	* @author: 千锋讲师张增强
	* @createTime: 2017年7月5日 上午10:52:49
	* @history:
	* @param request
	* @param response
	* @throws ServletException
	* @throws IOException
	* @throws NumberFormatException
	* @throws SQLException void
	 */
	protected void findProduct(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, NumberFormatException, SQLException {
		int pageSize=6;
		int currentPage=1;
		String currentPage_=request.getParameter("currentPage");
		String name = request.getParameter("name");
		if(currentPage_!=null&&!"".equals(currentPage_)){
			currentPage=Integer.parseInt(currentPage_);
		}
		//调用
		PageBean pb=productServiceImpl.findProductByPage(currentPage, pageSize, name);
		
		request.setAttribute("name", name);
		request.setAttribute("pb", pb);
		request.getRequestDispatcher("product_list1.jsp").forward(request, response);

	}
	/**
	 * 商品详情页
	* @author: 千锋讲师张增强
	* @createTime: 2017年7月5日 上午11:24:37
	* @history:
	* @param request
	* @param response
	* @throws ServletException
	* @throws IOException
	* @throws SQLException void
	 */
	protected void productDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
		String pid = request.getParameter("pid");
		Product p=productServiceImpl.pruductDetail(pid);
		Category c=categoryServiceImpl.findByCid(p.getCid());
		request.setAttribute("p", p);
		request.setAttribute("c", c);
		request.getRequestDispatcher("product_info.jsp").forward(request, response);
	}
	/**
	 * 商品添加到购物车
	* @author: 千锋讲师张增强
	* @createTime: 2017年7月5日 上午11:24:48
	* @history:
	* @param request
	* @param response
	* @throws ServletException
	* @throws IOException
	* @throws SQLException void
	 */
	protected void addProductToCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
		//获取商品
		String pid = request.getParameter("pid");
		Product p=productServiceImpl.pruductDetail(pid);
		//获得购买的数量
		int buyNum = Integer.parseInt(request.getParameter("buyNum"));
		
		/**
		 * 获得购物车
		 */
		Cart cart = (Cart) request.getSession().getAttribute("cart");
		if(cart==null){
			cart=new Cart();
		}
		//获得购物项的容器
		Map<String, CartItem> cartItems = cart.getCartItems();
		//准备购物项
		CartItem item=new CartItem();
		/**
		 * 添加购物项的的时候，要进行判断，判断原来的购物车中是否有该商品，如果有该商品：数量+buyNum,subTotal+=buyNum*p.getShop_price();
		 * 如果原购物车中没有该商品，直接添加商品。
		 */
		if(cartItems.containsKey(pid)){//原来购物车中有该商品
			//取出该购物项
			 item = cartItems.get(pid);
			 //数量+buyNum
			 item.setBuyNum(item.getBuyNum()+buyNum);
			 //小计
			 item.setSubTotal(item.getSubTotal()+buyNum*p.getShop_price());
		}else{//原来购物车中没有该商品
			item.setBuyNum(buyNum);
			item.setProduct(p);
			item.setSubTotal(p.getShop_price()*buyNum);
			/*cartItems.put(pid, item);
			//把购物项添加到购物项的容器里
			cart.setCartItems(cartItems);
			//总计
			cart.setTotal(cart.getTotal()+p.getShop_price()*buyNum);*/
		}	
		
		
			//把购物项添加到购物项的容器里
			 cartItems.put(pid, item);
				cart.setCartItems(cartItems);
				//总计
				cart.setTotal(cart.getTotal()+p.getShop_price()*buyNum);
		/**
		 * 把购物车存储到session
		 */
		request.getSession().setAttribute("cart", cart);
		//跳转到购物车界面
		response.sendRedirect("cart.jsp");

	}
	protected void deleteProductFromCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
			//现获得要删除的商品
			String pid = request.getParameter("pid");
			
			//从session里获得购物车
			Cart cart = (Cart) request.getSession().getAttribute("cart");
			if(cart!=null){
				
				Map<String, CartItem> cartItems = cart.getCartItems();
				//删除的商品的小计
				double subTotal = cartItems.get(pid).getSubTotal();
				//购物车中的价钱要改变
				cart.setTotal(cart.getTotal()-subTotal);
				//从购物车中删除该商品
				cartItems.remove(pid);
				request.getSession().setAttribute("cart", cart);
			}
		response.sendRedirect("cart.jsp");
		
	}
	protected void adminAddProduct(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, FileUploadException {
		/**
		 * 存储表单的key和 value值
		 */
		Map <String,Object> map=new HashMap<>();
		DiskFileItemFactory factory=new DiskFileItemFactory();
		ServletFileUpload upload=new ServletFileUpload(factory);
		/**
		 * ServletFileUpload
		 * 	parseRequest用来解析表单数据的
		 * 把表单数据的key和value的信息封装成 FileItem对象
		 */
		List<FileItem> parseRequest = upload.parseRequest(request);
		/**
		 * setHeaderEncoding设置请求编码
		 */
		upload.setHeaderEncoding("utf-8");
		for(FileItem f: parseRequest){
			/**
			 * FileItem
			 * 		isFormField()用来判断该对象是否普通的表单数据
			 * 		getFieldName()获得name属性值
			 * 		getString()获得该对象value属性值
			 */
			boolean formField = f.isFormField();
			if(formField){
				String fieldName = f.getFieldName();
				String value = f.getString("utf-8");
				map.put(fieldName, value);
			}
			else{//就是流文件
				/**
				 * getInputStream()获得该文件的输入流
				 */
				InputStream in = f.getInputStream();//文件的输入流
				//文件要存储的路径
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss_SSS");
				/**
				 * 文件路径是：D:\java_all\cdj2e1703-tomcat-8.0.43-x64\apache-tomcat-8.0.43\webapps\bk\products\ upload
				 * 文件名：32位的uuid_时间戳
				 */
				String name=CommonsUtils.getUUID()+"_"+sdf.format(new Date())+".jpg";
				String realPath = ((GenericServlet) request).getServletContext().getRealPath("/products/upload/"+name);
				/**
				 * 输出流
				 */
				FileOutputStream os=new FileOutputStream(new File(realPath));
				/**
				 * 文件复制的方法
				 */
				IOUtils.copy(in, os);
				os.close();
				in.close();
				Product p=new Product();
				String pimage=request.getContextPath()+"/upload"+name;
				p.setPimage(pimage);
				
				
				
				
			}
			
		}
		
		System.out.println(map);
		
	response.sendRedirect("cart.jsp");
	
}
}